package com.example.demo.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static java.util.Calendar.*;

public class DateSolve {

    /**
     * 获取过去第几天的日期
     *
     * @param past
     * @return
     */
    public static String getPastDate(int past, Date date) {
        Calendar calendar = getInstance();
        calendar.setTime(date);
        calendar.set(DATE, calendar.get(DATE) - past);
        Date today = calendar.getTime();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String result = sdf.format(today);
        return result;
    }

    /**
     * 获取过去7天内的日期数组
     *
     * @return 日期数组
     */
    public static String[] pastDay(int days) {
        String pastDaysList[] = null;
        try {
            //我这里传来的时间是个string类型的，所以要先转为date类型的。
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String time = sdf.format(new Date());
            Date date = sdf.parse(time);
            pastDaysList = new String[days];
            for (int i = days - 1; i >= 0; i--) {
                pastDaysList[i] = getPastDate(i, date);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return pastDaysList;
    }
}
